<script>
import EChatHeader from "@/components/common/EChatHeader.vue";
import EChatNav from "@/components/common/EChatNav.vue";
import FriendItem from "@/components/friend/FriendItem.vue";
import AddFriend from "@/components/friend/AddFriend.vue";
import HeadImage from "@/components/common/HeadImage.vue";
import {Dialog} from "vant";

export default {
  name: "AddFriend",
  components: {
    EChatNav, EChatHeader,
    FriendItem,
    AddFriend,
    HeadImage
  },
  data() {
    return {
      searchUsername: "",
      searchText: "",
      showAddFriend: false,
      activeIdx: -1,
      userInfo: {},
      users: [],
    }
  },
  methods: {
    onClose() {
      this.$emit("close");
    },
    onSearch() {
      if (!this.searchText) {
        this.users = [];
        return;
      }
      this.$http({
        url: "/user/findByName",
        method: "post",
        params: {
          name: this.searchText
        }
      }).then((data) => {
        this.users = data;
      })
    },
    isFriend(userId) {
      let friends = this.$store.state.friendStore.friends;
      let friend = friends.find((f) => f.id == userId);
      return friend != undefined;
    },
    onShowAddFriend() {
      this.showAddFriend = true;
    },
    onCloseAddFriend() {
      this.showAddFriend = false;
    },
    onActiveItem(friend, idx) {
      this.$store.commit("activeFriend", idx);
      this.activeIdx = idx
      this.loadUserInfo(friend, idx);
    },
    onDelItem(friend, idx) {
      Dialog.confirm({
        title: 'Confirm release',
        message: `Confirm delete'${friend.nickName}',and clear the chat history?`,
        confirmButtonColor: 'var(--chat-theme-color)',
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
      }).then(() => {
        this.$http({
          url: "/friend/delete",
          method: 'POST',
          params: {
            friendId: friend.id
          }
        }).then((data) => {
          this.$message.success("Successfully deleted friend");
          this.$store.commit("removeFriend", idx);
          this.$store.commit("removePrivateChat", friend.id);
        })
      })
    },
    onAddFriend(user) {
      this.$http({
        url: "/friend/add",
        method: "POST",
        params: {
          friendId: user.id
        }
      }).then((data) => {
        this.$message.success("Added successfully, the other party has become your friend");
        let friend = {
          id: user.id,
          nickName: user.nickName,
          headImage: user.headImage,
          online: user.online
        }
        this.$store.commit("addFriend", friend);
        console.log('friends', this.$store.state.friendStore.friends)
      })
    },
    onSendMessage(user) {
      let chat = {
        type: 'PRIVATE',
        targetId: user.id,
        showName: user.nickName,
        headImage: user.headImageThumb,
      };
      this.$store.commit("openChat", chat);
      this.$store.commit("activeChat", 0);
      this.$router.push("/home/chat");
      this.$store.commit('commonData/setIsShowChatConversation', false)
    },
    showFullImage() {
      if (this.userInfo.headImage) {
        this.$store.commit('showFullImageBox', this.userInfo.headImage);
      }
    },
    updateFriendInfo(friend, user, index) {
      // The data in the store cannot be directly modified, a deep copy of the store's data is required
      friend = JSON.parse(JSON.stringify(friend));
      friend.headImage = user.headImageThumb;
      friend.nickName = user.nickName;
      this.$http({
        url: "/friend/update",
        method: "POST",
        data: friend
      }).then(() => {
        this.$store.commit("updateFriend", friend);
        this.$store.commit("updateChatFromFriend", user);
      })
    },
    loadUserInfo(friend, index) {
      this.$http({
        url: "/user/find",
        method: "POST",
        params: {
          id: friend.id
        }
      }).then((user) => {
        this.userInfo = user;
        // If you find that your friend's avatar and nickname have changed, update them
        if (user.headImageThumb != friend.headImage ||
            user.nickName != friend.nickName) {
          this.updateFriendInfo(friend, user, index)
        }
      })
    }
  },
  computed: {
    friendStore() {
      return this.$store.state.friendStore;
    }
    // isFriend() {
    //   return this.friendStore.friends.find((f) => f.id == this.userInfo.id);
    // }
  }
}
</script>

<template>
  <div class="home-search-page">
    <EChatHeader></EChatHeader>
    <div class="add-friend-content">
      <van-search
          class="search-friend-container"
          v-model="searchText"
          placeholder="Enter Username To Search"
          @input="onSearch()"
      />
      <div class="empty-container" v-if="users.length === 0">
        <div class="empty-icon"></div>
      </div>
      <div class="search-friend-list-container" v-else>
        <div v-for="(user) in users" :key="user.id" v-show="user.id != $store.state.userStore.userInfo.id">
          <div class="item">
            <div class="avatar">
              <head-image :name="user.nickName" :url="user.headImage" :online="user.online"></head-image>
            </div>
            <div class="add-friend-text">
              <div class="text-user-name">
                <div>{{ user.userName }}</div>
                <div :class="user.online ? 'online-status  online' : 'online-status'">{{
                    user.online ? "  [online]" : "  [offline]"
                  }}
                </div>
              </div>
              <div class="text-nick-name">
                <div>Nickname: {{ user.nickName }}</div>
              </div>
            </div>
            <div class="added-btn" v-show="!isFriend(user.id)" @click="onAddFriend(user)">
              <img class="flex-center" src="../assets/image/all/add-friend-icon.png" alt="add">
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.friend-item-single {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 42px;

  .friend-avatar {
    align-self: center;
  }

  .friend-name-container {
    margin-left: 16px;
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .username-text {

    }

    .nickname-text {

    }
  }

  .option-btn {
    align-self: center;

    .added-btn, .unadded-btn {
      width: 20px;
      height: 22px;

      img {
        width: 100%;
        height: 100%;
      }
    }
  }
}

.home-search-page {
  display: flex;
  width: 100%;
  height: 100%;
}

.add-friend-content {
  margin-top: 110px;
  width: 100%;
  height: calc(100vh - 110px);
  flex: 1;
  background: var(--chat-content-bg);
  overflow-y: auto;
  padding: 32px 24px;
  display: flex;
  flex-direction: column;
  align-items: center;

  .search-friend-container {
    width: 100vw;
    height: 56px;
  }

  .search-friend-container.van-search {
    padding: 0 !important;
    width: 100%;
    height: 56px;
    opacity: 1;
    border-radius: 8px;
    border: 1px solid var(--search-username-border-color);

    .van-search__content {
      background: transparent;

      .van-cell {
        height: 56px;
        display: flex;
        align-items: center;
      }
    }
  }

  .search-friend-list-container {
    width: 100%;
    flex: 1;
    margin-top: 24px;
    overflow-y: auto;

    .added-btn, .unadded-btn {
      width: 20px;
      height: 22px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .item {
      height: 65px;
      display: flex;
      position: relative;
      align-items: center;

      .avatar {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .add-friend-text {
        flex: 1;
        display: flex;
        height: 50px;
        flex-direction: column;
        justify-content: space-between;
        padding-left: 15px;
        text-align: left;
        overflow: hidden;

        .text-user-name {
          display: flex;
          flex-direction: row;
          font-weight: 600;
          font-size: 16px;
          line-height: 25px;
          align-self: start;
          color: var(--chat-name-text-color);

          .online-status {
            margin-left: 2px;
            font-size: 12px;
            font-weight: 600;

            &.online {
              color: var(--user-online-online);
            }
          }
        }

        .text-nick-name {
          display: flex;
          flex-direction: row;
          font-size: 12px;
          line-height: 22px;
          align-items: end;
          color: var(--chat-nickname-text-color);
        }
      }
    }
  }

  .empty-container {
    flex: 1;
    margin-top: 110px;

    .empty-icon {
      width: 287px;
      height: 240px;
      background-image: var(--search-friend-empty-image);
      background-position: center center;
    }
  }
}
</style>